<html>
<head>
<title>TurKit Editor</title>
<style type="text/css">
body {
	margin: 0;
	padding: 0;
}

textarea {
	margin: 0;
	padding: 0;
	border: none;
}

.iconButton {
	position: absolute;
	left: 0px;
	top: 0px;
	cursor: pointer;
	width: 16px;
	height: 16px;
	z-index: 100;
}

.hide {
	visibility: hidden;
}

.saveButton {
	background-image: url('icons/save_grey.png');
}

div.saveButton:hover {
	background-image: url('icons/save.png');
}

.reloadButton {
	background-image: url('icons/reload_grey.png');
}

div.reloadButton:hover {
	background-image: url('icons/reload.png');
}

.error {
	border: 2px solid #ff0000;
	background-color: #ffa0a0;
	padding: 5px;
}

</style>
</head>
<body>
<script src="jquery.js"> </script>
<script src="tab.js"> </script>
<script src="myutil.js"> </script>
<script>

___COMMON___

var readonly = ___READONLY___

function positionButtons() {
    var leftMost = $(window).width()
    
    var editor = $('#editor').get(0)    
	var isVerticalScrollbar = editor.scrollHeight > editor.clientHeight;
	if (isVerticalScrollbar) {
		leftMost -= 16
	}
    
    $('.saveButton').css("left", (leftMost - 32) + "px")
    $('.reloadButton').css("left", (leftMost - 16) + "px")
}

function onResize() {
	positionButtons()
}

var saveTimeout = 0
function queueSave() {
	dequeueSave()
	dirty = true
	$('.saveButton').css('visibility', 'visible')
    saveTimeout = setTimeout(save, 2000)
}
function dequeueSave() {
	clearTimeout(saveTimeout)
}

var dirty = false
function save(cont) {
	if ((typeof cont) != "function") cont = function () {}

	dequeueSave()
	if (dirty) {
		dirty = false
	    ajaxCont('/api', {
	        "method" : "setFileContents",
	        "file" : file.key,
	        "contents" : $('#editor').val()
	    }, function (e) {
		    if (!dirty)
			    $('.saveButton').css('visibility', 'hidden') 
		}, cont)
	} else {
		cont()
	}
}

var oldIsVerticalScrollBar = false
var oldValue = null
function onChange() {
	var editor = $('#editor')
	if (oldValue == null || editor.val() != oldValue) {
		oldValue = editor.val()
		queueSave()
	}

	editor = editor.get(0)
	var isVerticalScrollbar = editor.scrollHeight > editor.clientHeight;
	if (isVerticalScrollbar != oldIsVerticalScrollBar) {
		oldIsVerticalScrollBar = isVerticalScrollbar
		onResize()
	}
}

function reload(val) {
	if ((typeof val) == "string") {
		if (oldValue == null || val != oldValue) {
			oldValue = val
	
			var editor = $('#editor')
			var scrollTop = editor.get(0).scrollTop
			editor.val(val)
	        editor.get(0).scrollTop = scrollTop
	        
		    // show errors here
		    $('#errorBox').empty()
		    if (file.name == "output") {
		    	function createError(message, subMessage) {
		    		var line = val.match(/\(main\.js:(\d+)\)/)
		    		if (line) {
		    			line = "<br><small>see main.js, line: " + line[1] + "</small>"
		    		} else {
		    			line = ""
		    		}
		    		$('#errorBox').append('<div class="error"><b>' + escapeXml(message) + '</b><br>' + escapeXml(subMessage) + line + '</div>') 
		    	}
		    	var m = null
		    	if (val.match(/<Code>AWS\.NotAuthorized<\/Code>/)) {
		    		createError("AWS Credentials are wrong", "Did you fill them out in the upper left corner?")
		    	} else if (val.match(/<Code>AWS\.MechanicalTurk\.XMLParseError<\/Code>/)) {
		    		createError("XML question data for HIT is wrong", "There may be a namespace issue...")
		    	} else if (val.match(/org.mozilla.javascript.JavaScriptException: saw:/)) {
		    		createError("Script out of sync with execution trace", "You can fix this by reseting the database.")
				} else if (m = val.match(/ReferenceError: "([^"]+)" is not defined/)) {
					createError('"' + m[1] + '" is not defined', "you may be reading a variable before ever setting it")
				} else if (m = val.match(/MTurk error: (\S+) failed/)) {
					createError("MTurk error with " + m[1], "Read the error in the output above for more details.")
				} else if (val.match(/\(main\.js:(\d+)\)/)) {
					createError("Unknown error", "Read the error in the output above for more details.")
				} else if (val.match(/org\.mozilla\.javascript\.JavaScriptException/)) {
					createError("Unknown error", "Read the error in the output above for more details.")
				}
		    }
	        
	        onResize()
		}
	} else {
		cont = val
		if ((typeof cont) != "function") cont = function () {}

	    ajaxCont('/api', {
	        "method" : "getFile",
	        "file" : file.key
	    }, function (e) {
		    file = eval(e)
		    reload(file.contents)
		}, cont)
	}
}

function reloadPoll() {
	setTimeout(function () {
		reload(reloadPoll)
	}, 5000)
}

$(function () {
	file = eval($('#file').val())
	
    reload(file.contents)
	if (readonly) {
		$('#editor').attr("readonly", "readonly")
		reloadPoll()
	} else {
		$('#editor').
	        bind('keydown', onChange).
	        bind('keyup', onChange).
	        bind('keypress', onChange).
	        bind('change', onChange)
	}

	$(window).resize(onResize)
    $('.saveButton').click(save)
    $('.reloadButton').click(reload)
    $('.saveButton').css('visibility', 'hidden')
})

</script>

<textarea style="display:none" id="file">___FILE___</textarea>
<div class="saveButton iconButton"></div>
<div class="reloadButton iconButton"></div>
<table style="width: 100%; height: 100%">
<tr style="width: 100%; height: 100%"><td style="width: 100%; height: 100%">
<textarea id="editor" style="width: 100%; height: 100%" onkeydown="checkTab(event)"></textarea>
</td></tr>
<tr><td><div id="errorBox"></div></div></td></tr>
</table>

</body>
</html>
